package org.facyt.vacas;

import org.facyt.commons.util.Constantes;
import org.facyt.commons.util.VaadinUtil;
import org.facyt.commons.view.errors.CustomErrorHandler;
import org.facyt.commons.view.errors.ErrorHandler;
import org.facyt.commons.view.interfaces.IWindow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import com.vaadin.Application;
import com.vaadin.ui.Window;

@Component
@Scope(WebApplicationContext.SCOPE_SESSION)
public class FacytApplication extends Application implements
		ApplicationContextAware {

	protected final Logger logger = LoggerFactory
			.getLogger(FacytApplication.class);

	private ApplicationContext applicationContext;

	private ErrorHandler errorHandler;
	
	@Autowired
	private MessageSource  messageSource;

	private static final long serialVersionUID = 1L;

	public FacytApplication() {
		super();

		errorHandler = new CustomErrorHandler();
	}

	@Override
	public void init() {

		setTheme("vacasWeb");
		VaadinUtil.application = this;
	}

	@Override
	public Window getWindow(String name) {
		Window window = super.getWindow(name);
		try {
			if (window == null) {
				window = (Window) applicationContext.getBean(name,
						IWindow.class);

				setMainWindow(window);
			}

		} catch (Exception e) {
			logger.error(Constantes.ErrorLoggin.ERROR, e);
		}

		return window;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;

	}

	@Override
	public void terminalError(com.vaadin.terminal.Terminal.ErrorEvent event) {
		if (errorHandler.isHandler(event)) {
			errorHandler.error(event);
		} else
			super.terminalError(event);
	}

}
